class Watcher {
    constructor() {
        this.callbacks = {};
    }

    watch(obj, prop, callback) {
        if (!(prop in obj)) {
            throw new Error(`${prop} does not exist on the object.`);
        }

        if (!this.callbacks[prop]) {
            this.callbacks[prop] = [];
        }

        this.callbacks[prop].push(callback);

        return new Proxy(obj, {
            set: (target, property, value) => {
                if (property === prop) {
                    this.callbacks[prop].forEach(cb => cb(value));
                }
                target[property] = value;
                return true;
            },
        });
    }
}


const watcher = new Watcher();

const obj = {
    name: 'Alice',
    age: 25,
};

const watchedObj = watcher.watch(obj, 'name', (newValue) => {
    console.log(`Name changed to ${newValue}`);
});

console.log(watchedObj.name); // 输出 "Alice"
watchedObj.name = 'Bob'; // 输出 "Name changed to Bob"
console.log(watchedObj.name); // 输出 "Bob"


const watchedObj = watcher.watch(obj, 'age', (newValue) => {
    console.log(`Name changed to ${newValue}`);
});

console.log(watchedObj.age); // 输出 "Alice"
watchedObj.age = 35; // 输出 "Name changed to Bob"
console.log(watchedObj.age); // 输出 "Bob"
